package com.thiswhyme.mq.rocketmq.producer.producer;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

import java.time.LocalDate;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by thiswhyme on 2020/6/7.
 */
@RocketMQTransactionListener
public class ThwmTransactionListener implements RocketMQLocalTransactionListener {

    /**
     * 保存返回unknown要回查消息的一些属性 那么所有对象都可以获取该消息回滚前的一些信息
     */
    private static ConcurrentHashMap<String, Object> infoMap = new ConcurrentHashMap<>();

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        String transId = (String) msg.getHeaders().get(RocketMQHeaders.PREFIX + RocketMQHeaders.TRANSACTION_ID);
        try {
            System.out.println(transId + "执行自定义操作");

            //提交
            return RocketMQLocalTransactionState.COMMIT;
//            //回滚
//            return RocketMQLocalTransactionState.ROLLBACK;
//            //待回查
//            return RocketMQLocalTransactionState.UNKNOWN;
        } catch (Exception e) {
            e.printStackTrace();
            infoMap.put(transId, LocalDate.now() + " 存放的快照信息");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String transId = (String) msg.getHeaders().get(RocketMQHeaders.PREFIX + RocketMQHeaders.TRANSACTION_ID);
        System.out.println(LocalDate.now() + " 回查：" + infoMap.get(transId));

        //提交
        return RocketMQLocalTransactionState.COMMIT;
//        //回滚
//        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
